import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';

import 'package:flutter_smart_heating/common/app.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:url_launcher/url_launcher.dart';

class UiHtml extends StatelessWidget {
  const UiHtml({
    super.key,
    this.data,
    this.fontSize = 16,
    this.dense = false,
  });
  final double fontSize;
  final String? data;
  final bool dense;
  @override
  Widget build(BuildContext context) {
    return Html(
      data: data,
      style: {
        "table": Style(
          backgroundColor: const Color.fromARGB(0x50, 0xee, 0xee, 0xee),
        ),
        "tr": Style(
          border: const Border(bottom: BorderSide(color: Colors.grey)),
        ),
        "th": Style(
          padding: HtmlPaddings.all(6),
          backgroundColor: Colors.grey,
        ),
        "td": Style(
          padding: HtmlPaddings.all(6),
          alignment: Alignment.topLeft,
        ),
        "p": Style(
          lineHeight: LineHeight.number(1.4),
          fontSize: FontSize(fontSize),
          margin: dense ? Margins.only(bottom: 10) : null,
        ),
        "body": Style(margin: Margins.zero),
        "div": Style(
          lineHeight: LineHeight.number(1.4),
          fontSize: FontSize(fontSize),
        ),
        "hr": Style(
          height: Height(2),
          margin: Margins.symmetric(vertical: 5),
        ),
        "img": Style(
          margin: Margins.zero,
          padding: HtmlPaddings.zero,
        )
      },
      extensions: [
        MatcherExtension(
          matcher: (p0) {
            return p0.elementName == 'video';
          },
          builder: (p0) {
            var url = p0.element!.attributes['src'].toString();
            return UiVideo(url: url);
          },
        ),
        ImageExtension(
          builder: (p0) {
            var url = p0.element!.attributes['src'].toString();
            return UiTap(
              onTap: () {
                ImagePreview.show(context, url: url);
              },
              child: Hero(
                tag: url,
                child: CachedNetworkImage(
                  imageUrl: url,
                ),
              ),
            );
          },
        ),
      ],
      onLinkTap: (url, attributes, element) {
        url = url.toString();
        if (url.startsWith('http')) {
          launchUrl(
            Uri.parse(url),
            mode: LaunchMode.externalApplication,
          );
        } else {
          App.push(url);
        }
      },
    );
  }
}
